﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Transactions;

namespace PMS_Service.CODE
{
    public class FileDict
    {
        private static PMSDataDataContext data = new PMSDataDataContext();

        private File _File;

        public File File
        {
            get { return _File; }
            set { _File = value; }
        }

        private Term _Term;

        public Term Term
        {
            get { return _Term; }
            set { _Term = value; }
        }

        public FileDict()
        {
            _File = new File();
            _Term = new Term();
        }

        public static bool InsertFile(string md5,string text)
        {
            if (data.Files.Where(m => m.FileMD5 == md5).Count() > 0)
            {
                File file = data.Files.First(m => m.FileMD5 == md5);


                if (data.Connection.State != System.Data.ConnectionState.Open)
                {
                    data.Connection.Open();
                }
                System.Data.Common.DbTransaction transaction = data.Connection.BeginTransaction();
                data.Transaction = transaction;
                try
                {
                    string[] s = text.Split(' ');
                    for (int i = 0; i < s.Length; i++)
                    {
                        Term trm = new Term { FileID = file.FileID, Term1 = s[i] };
                        data.Terms.InsertOnSubmit(trm);
                    }
                    data.SubmitChanges();
                    transaction.Commit();
                    data.Connection.Close();
                    return true;
                }
                catch (Exception)
                {
                    transaction.Rollback();
                    data.Connection.Close();
                    return false;
                }
            }
            else
            {
                return false;
            }


        }
    }
}
